package guida.ccf.gzuexaminesystem.security;

import com.alibaba.fastjson.annotation.JSONField;
import guida.ccf.gzuexaminesystem.entity.StudentInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 实现 UserDetails, 封装用户信息.
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginStudentInfo implements UserDetails {

    /**
     * 用户信息
     */
    private StudentInfo user;

    /**
     *  jwt 令牌
     */
    private String jwtId;

    /**
     *  用户权限信息
     */
    private List<String> permission;

    public LoginStudentInfo(StudentInfo user, List<String> authorities) {
        this.user = user;
        this.permission = authorities;
    }

    /**
     * 返回权限信息
     */
    @JSONField(serialize = false, deserialize = false) // 让 fastJson 不序列化 SimpleGrantedAuthority
    private List<SimpleGrantedAuthority> authorities; // 属性名要和方法名对应: authorities -> getAuthorities
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 把 authorities 中的权限信息封装成 GrantedAuthority 的实现类 SimpleGrantedAuthority
        if (authorities != null && authorities.size() > 0) {
            return authorities;
        }
        authorities =
                this.permission.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }

    /**
     * 获取密码
     */
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    /**
     * 获取用户名
     */
    @Override
    public String getUsername() {
        return user.getStudentId();
    }

    /**
     * 判断是否过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 判断用户的账户是否被锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 判断用户的密码是否过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 用户是否可用
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
